import { AbstractController, Restful, Router } from "@jingli/restful";
import { JLRequest, JLResponse } from '../types';
import { NextFunction } from 'express';
import doc from '@jingli/doc';
import { ParamsNotValidError, NotFoundError, NotPermitError } from "@jingli/error";
import { DB } from "../model/index";

@Restful()
export default class CategoryController extends AbstractController { 

    constructor() { 
        super();
    }

    $isValidId(id: string) { 
        return /^\d+$/.test(id);
    }

    @doc("增加日程分类")
    async add(req: JLRequest, res: JLResponse, next: NextFunction) { 
        let { uid } = req.session;
        let { name } = req.body;
        if (!name) { 
            throw new ParamsNotValidError("name");
        }
        let category = DB.models['Category'].build({
            name,
            uid,
        })
        category = await category.save();
        res.json(this.reply(0, category));
    }

    @doc("获取日程分类")
    async get(req: JLRequest, res: JLResponse, next: NextFunction) { 
        let { uid } = req.session;
        let { id } = req.params;
        let category = await DB.models['Category'].findById(id);
        if (!category) { 
            throw new NotFoundError('日程分类');
        }
        if (category.uid != uid) { 
            throw new NotPermitError('日程分类');
        }
        res.json(this.reply(0, category));
    }

    @doc("增加日程分类属性")
    @Router('/:id/attribute', 'POST')    
    async addCategoryAttribute(req: JLRequest, res: JLResponse, next: NextFunction) { 
        let { uid } = req.session;
        let { id } = req.params;
        let { name, description } = req.body;
        let category = await DB.models['Category'].findById(id);
        if (!category) { 
            throw new NotFoundError("日程分类");
        }
        if (category.uid != uid) { 
            throw new NotPermitError("日程分类");
        }

        let categoryAttribute = DB.models['CategoryAttribute'].build({
            category: id,
            name,
            description,
        });
        categoryAttribute = await categoryAttribute.save();
        res.json(this.reply(0, categoryAttribute));
    }

    @doc("获取日程分类属性")
    @Router('/:id/attribute')
    async getCategoryAttribute(req: JLRequest, res: JLResponse, next: NextFunction) { 
        let { uid } = req.session;
        let { id } = req.params;
        let { name, description } = req.body;
        let category = await DB.models['Category'].findById(id);
        if (!category) {
            throw new NotFoundError("日程分类");
        }
        if (category.uid != uid) {
            throw new NotPermitError("日程分类");
        }
        let attributes = await DB.models['CategoryAttribute'].findAll({
            where: {
                category: id,
            }
        });
        res.json(this.reply(0, attributes));
    }
}